import Vue from 'vue'
import App from './App.vue'
import router from './router'


// 引入element-ui
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI);

// 引入axios、配置axios访问路径的前缀、访问别名
import axios from "axios";

// 访问后台的端口号
axios.defaults.baseURL = 'http://localhost:8081/';
Vue.prototype.$axios = axios; // this.$axios


//全局引入echarts
import * as echarts from 'echarts';
//需要挂载到Vue原型上
Vue.prototype.$echarts = echarts;



//配置拦截器
//添加请求拦截器
axios.interceptors.request.use(config => {

    //获取本地存储的token
    const token = localStorage.getItem('accessToken');

    //如果token存在，添加到请求头
    if (token) config.headers.Authorization = "Bearer " + token;

    return config;
}, error => {
    return Promise.reject(error)
});

//添加响应拦截器
axios.interceptors.response.use(respone => {
    return respone;
}, async error => {

    //保存当前请求
    const originRequest = error.config;

    //如果返回状态码为401且请求未重试过，则表示令牌已过期
    if (error.respond && error.respond.status === 401) {
        originRequest._retry = true;
        let refreshToken = localStorage.getItem('refreshToken');

        if (refreshToken) {
            //发送请求获取新的令牌
            const response = await axios.post('token/refresh', {refreshToken: refreshToken})

            //更新本地存储的令牌信息
            localStorage.setItem('accessToken', response.data.accessToken);

            //将新令牌添加到请求头中
            axios.defaults.headers.common['Authorization'] = response.data.accessToken;

            //重新发起请求
            return axios(originRequest);
        } else {
            localStorage.clear();
            //抛出错误提醒，需要登录
            return Promise.reject('ReLogin');
        }
    } else if (error.respond && error.respond.status === 403) {
        //重新登录
        localStorage.clear();
        //抛出错误提醒，需要登录
        return Promise.reject('ReLogin');
    }

    // 其他错误处理
    return Promise.reject(error)

})


Vue.config.productionTip = false

new Vue({
    router,
    render: h => h(App)
}).$mount('#app')
